import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import router from '@/router'

let pending = [] // 声明一个数组用于存储每个axios请求的取消函数和axios标识
let cancelToken = axios.CancelToken
let removePending = (ever) => {
  for (let p in pending) {
    //当当前请求在数组中存在时执行函数体
    if (pending[p].u === ever.url + '&' + ever.method) {
      // 执行取消操作
      pending[p].f()
      // 把这条记录从数组中移除
      pending.splice(p, 1)
    }
  }
}

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: '/api',
    timeout: 60000
})

// 异常拦截处理器
const errorHandler = async (error) => {
  // 请求取消时，也会进入error，根据axios.isCancel()：true--请求取消  false--请求失败
  if (axios.isCancel(error)) return Promise.reject('取消重复请求')
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      storage.set(ACCESS_TOKEN, '')
      console.log('storage.get(ACCESS_TOKEN)', storage.get(ACCESS_TOKEN))
      if (storage.get(ACCESS_TOKEN)) {
       await store.dispatch('Logout')
      }
      await router.replace('/user/login')
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  }

  // 移除相同点击
  removePending(config)
  /**
   * 存储请求体
   */
  config.cancelToken = new cancelToken((c) => {
    // 这里的axios标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
    pending.push({ u: config.url + '&' + config.method, f: c })
  })

  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if (response.data.code !== 0) {
    notification.error({
      message: response.data.message,
    })
    return Promise.reject(response.data.message)
  }
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request
const axiosPromiseArr = pending
export {
  axiosPromiseArr,
  installer as VueAxios,
  request as axios
}
